package com.tinyseed.emcp.api.app.sharding;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

//日期分表策略

@Slf4j
public class DatePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {
    private static DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyyMM", Locale.CHINA);
    private static final String SEPERATOR = "_";//表名分隔符
    private static Date  lowwerDate = null;

    static {
        lowwerDate = DateUtil.parseDate("2020-05-01");
    }

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        String loginTableName = shardingValue.getLogicTableName();
        Date createTime = shardingValue.getValue();
        if(createTime == null || createTime.before(lowwerDate) ){
            log.info("创建时间为空，或者当前时间:{} 小于 2020-05 ，进入默认表",createTime);
            return loginTableName;
        }
        String yyyyMM = "";
        try{
            yyyyMM =SEPERATOR+ createTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(sdf);
            log.info("进入表：{}",loginTableName+yyyyMM);
            return loginTableName+yyyyMM;
        }catch(Exception e){
            log.error("解析创建时间异常，分表失败，进入默认表",e);
        }
        return loginTableName;
    }

}

